﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace StudentManegement.Controllers
{

    public class ErrorController : Controller
    {
        private ILogger<ErrorController> logger;

        /// <summary>
        /// 通过ASP.NET Coew 注入ILogger服务
        /// </summary>
        /// <param name="logger"></param>
        public ErrorController(ILogger<ErrorController> logger) 
        {
            this.logger = logger;
        }


        [Route("Error/{statusCode}")]
        public IActionResult HttpStatusCodeHandler(int statusCode)
        {
            var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();

            switch (statusCode)
            {
                case 404:
                    ViewBag.ErrorMessage = "抱歉，你访问的页面不存在";
                    logger.LogWarning($"访问URL:{statusCodeResult.OriginalPath},查询字符传={statusCodeResult.OriginalQueryString}不成功，状态码为{statusCode}");
                    ViewBag.Path = statusCodeResult.OriginalPath; //获取访问路径
                    ViewBag.QueryStr = statusCodeResult.OriginalQueryString; //获取参数
                    //ViewBag.BasePath = statusCodeResult.OriginalPathBase; 暂时未知
                    break;
                default:
                    break;
            }
            return View("NotFount");
        }

        [AllowAnonymous]
        [Route("NewError")]
        public IActionResult Error()
        {
            var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
            ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
            ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
            ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;

            return View("Errors");
        }
    }
}
